const path = require('path')
const fs = require('fs')
const fse = require('fs-extra')

const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

const resolve = p => {
  return path.resolve(__dirname, p)
}

const config = {
  pageTemplate: 'src/pages/',
  pageEnd: '/main.js'
}

const getPages = pages => {
  var pageConfig = {}
  pages.forEach(p => {
    if (typeof p === 'string') {
      pageConfig[p] = {
        entry: `${config.pageTemplate}${p}${config.pageEnd}`
      }
      const template = resolve(`./public/${p}.html`)
      if (fs.existsSync(template)) {
        pageConfig[p]['template'] = template
      }
    } else if (typeof p === 'object') {
      pageConfig[p.name] = {
        entry: p.entry
      }
      if (p.template) {
        pageConfig[p.name]['template'] = p.template
      }
    }
  })
  return pageConfig
}

/**
 * Puppeteer 所用的chrome执行文件路径
 */
const executablePath = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
// const executablePath = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'

const PrerenderPlugin = routes => {
  return new PrerenderSPAPlugin({
    staticDir: resolve('dist'),
    routes,
    minify: false,
    postProcess (renderedRoute) {
      // Ignore any redirects.
      renderedRoute.route = renderedRoute.originalRoute
      // Basic whitespace removal. (Don't use this in production.)
      renderedRoute.html = renderedRoute.html.split(/>[\s]+</gmi).join('><')
      // Remove /index.html from the output path if the dir name ends with a .html file extension.
      // For example: /dist/dir/special.html/index.html -> /dist/dir/special.html
      if (renderedRoute.route.endsWith('.html')) {
        renderedRoute.outputPath = path.join(__dirname, 'dist', renderedRoute.route)
      } else {
        renderedRoute.outputPath = path.join(__dirname, 'dist', `${renderedRoute.route}.html`)
      }

      return renderedRoute
    },
    renderer: new Renderer({
      executablePath
    })
  })
}

const pluginName = 'JpressPlugin'
class JpressPlugin {
  constructor (options) {
    this.options = options
  }
  apply (compiler) {
    compiler.hooks.done.tap(pluginName, (stats) => {
      setTimeout(() => {
        const walk = (dir) => {
          var results = []
          var list = fs.readdirSync(dir)
          // console.log(list)
          for (let i = 0; i < list.length; i++) {
            const file = dir + '/' + list[i]
            if (!file.endsWith('.html') && !file.endsWith('.htm')) {
              continue
            }
            var stat = fs.statSync(file)
            if (stat && stat.isDirectory()) results = results.concat(walk(file))
            else results.push(file)
          }
          return results
        }
        const rs = walk(resolve('./dist'))
        rs.forEach(file => {
          const html = fs.readFileSync(file)
          fse.copySync(resolve('.broswer'), resolve('./dist'))
          fs.writeFileSync(file, html.toString()
            .replace('<html><head></head><body>', '')
            .replace('</body></html>', '')
            .replace(/[\r\n][\r\n]/g, '\n') // 2行->1行
            .replace(/[\r\n][\r\n][\r\n]/g, '\n') // 3行->1行
            .replace('<script type="text/javascript" src="/js/chunk-vendors.js"></script>', '')
            .replace(/script></g, 'script>\n<')
          )
        })
        fs.unlink(resolve('./dist/js/chunk-vendors.js'), () => { })
        console.log('jpress plugin')
      }, 0)
    })
  }
}

module.exports = {
  getPages,
  executablePath,
  PrerenderPlugin,
  JpressPlugin
}
